
<?php
class Array2XML {
	private $writer;
	private $version = '1.0';
	private $encoding = 'UTF-8';
	private $rootName = 'root';
	private $fileName = "result.xml";

	function Array2XML($fileName = null) {
		$this->writer = new XMLWriter();
		
		if(isset($fileName)) {
			$this->fileName = $fileName;
		}
	}

	public function convert($data) {
//		$this->writer->openMemory();
		if($this->writer->openURI($this->fileName) == false) {
			throw new Exception("Error open URI $this->fileName");
		}
		$this->writer->setIndent(true);
		$this->writer->startDocument($this->version, $this->encoding);
		$this->writer->startElement($this->rootName);
		if (is_array($data)) {
			$this->getXML($data);
		}
		$this->writer->endElement();
		return $this->writer->flush();
//		return $this->writer->outputMemory();
	}
	
	private function getXML($data) {
		// С начала обрабатываются параметры, затем вложенные массивы
		
		foreach ($data as $key => $val) {
			if (!is_numeric($key) and !is_array($val)) {
				$this->writer->writeAttribute($key, $val);
			}
		}
		
		foreach ($data as $key => $val) {
			if (is_numeric($key)) {
//				$key = 'key'.$key;
				$this->getXML($val);

			} else if (is_array($val)) {
//				print $key."\n";
				$this->writer->startElement($key);
				$this->getXML($val);
				$this->writer->endElement();
			}
		}
	}

	public function setVersion($version) {
		$this->version = $version;
	}

	public function setEncoding($encoding) {
		$this->encoding = $encoding;
	}

	public function setRootName($rootName) {
		$this->rootName = $rootName;
	}

}
//end of Array2XML.php
